import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { Loading } from 'element-ui'
import qs from 'querystring'
// import router from '@/router'
let loadingInstance
let loadCount = 0
// create an axios instance
const service = axios.create({
  baseURL: public_config.base_api, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 如果 skipInterceptor 为 true，直接返回 config，跳过拦截器
    if (config.skipInterceptor) {
      return config
    }

    const isLoading = (config.headers || {}).isLoading === false
    // console.log('loadCount', loadCount)
    // console.log(config.url)
    if (!isLoading && loadCount <= 0) {
      loadingInstance = Loading.service({
        fullscreen: true,
        background: 'rgba(255,255,255,0.6)',
        text: '加载中'
      })
    }
    !isLoading && loadCount++
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['Accept-Language'] = 'zh-Hans,zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6'
    }
    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params)
      }
    }
    console.log('config', config)
    // // 调用iot接口
    // if (config.url.search('/iot-os-hcnet') !== -1) {
    //   config.url = 'http://dev.oranllc.com/iot-os-hcnet' + config.url.replace('/iot-os-hcnet', '')
    //   // console.log('config.url 二期', config.url)
    // } else if (config.url.search('/iot-os') !== -1) {
    //   // 调用iot接口
    //   config.url = public_config.iot_os_api + config.url.replace('/iot-os', '')
    // } else if (config.url.search('/weighbridge_api') !== -1) {
    //   // 地磅中控接口
    //   config.url = public_config.weighbridge_api + config.url.replace('/weighbridge_api', '')
    // }

    // if (config.url.search('/base') !== -1) {
    //   config.url = public_config.configuration_api + config.url.replace('/base', '')
    // }

    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    setTimeout(() => {
      loadCount--
      // if (loadCount === 0) {
      loadingInstance.close()
      // }
    }, 10)
    // // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    if (response.error) {
      return Promise.reject(new Error(response.error.message || 'Error'))
    } else if (response.status === 204) {
      return response
    } else {
      return res
    }
  },
  (error) => {
    // console.log('err',error.response)
    // console.log('err' + error) // for debug
    setTimeout(() => {
      loadCount--
      if (loadCount === 0) {
        loadingInstance.close()
      }
    }, 10)

   
    if (error.response.status === 401) {
      
      

      Message({
        message: '登陆信息已过期,请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      return false
      // store.dispatch('user/resetToken').then(() => {
      //   location.reload()
      // })
    } else {
      // message: !error.response ? error : error.response.data.error ? (error.response.data.error.message + ' ' + error.response.data.error.code) : error.message,
      Message({
        message: !error.response
          ? error
          : error.response.data.error
          ? error.response.data.error.message
          : error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
